
package view.drawable;

import test.Application;
import view.JCanvas;
import view.JCanvasMouseAdapter;

import java.awt.*;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;

public class MoveDrawableMouseListener extends JCanvasMouseAdapter {

    protected ArrayList<IMovableDrawable> drawable = new ArrayList<IMovableDrawable>();
    private Point lastDraggedPosition;

    /**
     * @param canvas
     */
    public MoveDrawableMouseListener(JCanvas canvas) {
        super(canvas);
    }

    /*
     * (non-Javadoc)
     *
     * @see java.awt.event.MouseMotionListener#mouseDragged(java.awt.event.MouseEvent)
     */
    public void mouseDragged(MouseEvent e) {
        if (lastDraggedPosition != null) {
            if (!drawable.isEmpty()) {
                for (IMovableDrawable drawable1 : drawable) {
                    drawable1.setPosition(new Point((int) (drawable1.getPosition().x + (e.getX() - lastDraggedPosition.getX())),
                            (int)(drawable1.getPosition().y + (e.getY() - lastDraggedPosition.getY()))));
                }
                canvas.repaint();
            } else {
                JCanvas jCanvas = Application.getWindowS().getjCanvas();
                jCanvas.setTranslate_x((jCanvas.getTranslate_x() + ((e.getX() - lastDraggedPosition.getX())/jCanvas.getScale())));
                jCanvas.setTranslate_y((jCanvas.getTranslate_y() + ((e.getY() - lastDraggedPosition.getY())/jCanvas.getScale())));
                canvas.repaint();
            }
        }
        lastDraggedPosition = e.getPoint();
    }

    /*
     * (non-Javadoc)
     *
     * @see java.awt.event.MouseListener#mousePressed(java.awt.event.MouseEvent)
     */
    public void mousePressed(MouseEvent e) {
        JCanvas jCanvas = Application.getWindowS().getjCanvas();

        if (!e.isControlDown())
            drawable.clear();

        List selectedDrawables = canvas.findDrawables(jCanvas.transformInversePoint(e.getPoint()));
        if (selectedDrawables.size() == 0)
            return;

        drawable.add((IMovableDrawable) selectedDrawables.get(0));

    }

    /*
     * (non-Javadoc)
     *
     * @see java.awt.event.MouseListener#mouseReleased(java.awt.event.MouseEvent)
     */
    public void mouseReleased(MouseEvent e) {
        lastDraggedPosition = null;
    }

}